package cn.framelife.rainbow.db.creator.part;

import java.util.Set;

import cn.framelife.rainbow.db.entity.ClazzProperty;
import cn.framelife.rainbow.db.entity.ImportSet;
import cn.framelife.rainbow.util.FreemarkerUtil;
import cn.framelife.rainbow.util.StringUtil;

public class DaoCreator {
	private String projectName;
	private String packageURL;
	
	public DaoCreator(String projectName, String packageURL) {
		this.projectName = projectName;
		this.packageURL = packageURL;
	}
	
	public void createCodeForEntityDao(ClazzProperty entity) throws Exception{
		ClazzProperty entityIDao = createIDao( entity);
		FreemarkerUtil.createEntityIDao(entityIDao);
		ClazzProperty entityDao = createDao( entityIDao, entity);
		FreemarkerUtil.createEntityDao(entityDao);
	}
	
	/**
	 * 生成实体类相关的Dao接口对象
	 *
	 * @param reverseProperty
	 * @param iDao
	 * @param entity
	 * @return
	 * @throws Exception
	 */
	private ClazzProperty createIDao(ClazzProperty entity) throws Exception {
		Set<String> imports = new ImportSet<String>();
		ClazzProperty entityIDao = new ClazzProperty();
		entityIDao.setClassName(StringUtil.merge("I",entity.getClassName(),"Dao"));
		entityIDao.setProjectName(projectName);
		
		entityIDao.setPackageURL(StringUtil.merge(packageURL,".dao"));
		entityIDao.setImports(imports);
	
		return entityIDao;
	}
	
	/**
	 * 生成实体类相关的Dao对象
	 *
	 * @param reverseProperty
	 * @param dao
	 * @param entityIDao
	 * @param entity
	 * @return
	 * @throws Exception
	 */
	private ClazzProperty createDao(ClazzProperty entityIDao,ClazzProperty entity) throws Exception {
		Set<String> imports = new ImportSet<String>();
		ClazzProperty entityDao = new ClazzProperty();
		entityDao.setClassName(StringUtil.merge(entity.getClassName(),"Dao"));
		entityDao.setProjectName(projectName);
		
		entityDao.setPackageURL(StringUtil.merge(packageURL,".dao.impl"));
		
		imports.add(entity.getPkType().getJavaTypePackage());
		imports.add(StringUtil.merge(entityIDao.getPackageURL(),".",entityIDao.getClassName()));
		imports.add(StringUtil.merge(entity.getPackageURL(),".",entity.getClassName()));
		
		entityDao.setInterfaceName(entityIDao.getClassName());
		entityDao.setImports(imports);
		entityDao.setEntityName(entity.getClassName());
		entityDao.setPkType(entity.getPkType());
		
		return entityDao;
	}
}
